var params = app.getRequestParams();
var txt1 = params.type == 1 ? '付款':'收款';
var txt2 = params.type == 1 ? '收款':'付款';
var tcode = params.type == 1 ? 'SK':'FK';
if(params.type == 1){
    params.relationType = 2;
}else{
    params.relationType = 1;
}
$(function(){
    $('#relationId_txt').html(txt1+$('#relationId_txt').html());
    $('#employeeId_txt').html(txt2+$('#employeeId_txt').html());


    app.request({
        url:'account/select',
        success:function (resp) {
            initPage(resp.data);
        }
    });
    
    $('#employeeId').combobox({
        width:160,noDefault:true,
        url:'user/select',
        name:'order.receiptUserId',
        valueField:'id',
        textField:'name'
    });
    $('#employeeId').combobox('setValue',app.getLogin().loginUserId,app.getLogin().loginName);

});

function initPage(accountData) {
    $('#fixtable_zu').fixgrid({
        noscroll:true,
        width:950,
        columns:[
            [
                {field:'serialnumber',title:'',width:30},
                {field:'o',title:'操作',width:60,formatter:function () {
                        return gridOpt('#fixtable_zu');
                    }},
            ],[
                {field:'name',title:'<span class="red">*</span>账户名称',width:120,editor:'combobox',
                    getData:function(cell,callback){
                        return callback(accountData);
                    },comboboxData:function (that) {
                        return $(that).data();
                    }
                },
                {field:'price',title:'<span class="red">*</span>'+txt2+'金额',width:120,editor:'decimal'},
                {field:'remarks',title:'备注',width:300,editor:'text'}
            ]
        ]
    });

    $('#fixtable_ge').fixgrid({
        noscroll:true,
        width:950,
        columns:[
            [
                {field:'serialnumber',title:'',width:30},
                {field:'o',title:'操作',width:60,formatter:function () {
                        return gridOpt('#fixtable_ge');
                    }},
            ],[
                {field:'orderType',title:'业务类别',width:120},
                {field:'date',title:'单据日期',width:120,n:'date'},
                {field:'code',title:'单据编号',width:120},
                {field:'orderMoney',title:'单据金额',width:120,n:'money'},
                {field:'verificateMoney',title:'已核销金额',width:120,n:'money'},
                {field:'xxx',title:'未核销金额',width:120,n:'money'},
                {field:'currVerificateMoney',title:'<span class="red">*</span>核销金额',width:100,n:'money',editor:'decimal'}
            ]
        ]
    });

    var choseOrderBtn = $('<button class="button" id="choseOrder"><span>选择源单</span></button>');
    choseOrderBtn.css({"margin-left":($('#fixtable_ge').width()-100)+"px"});
    $('#choseOrderDiv').append(choseOrderBtn);

    if(params.status==2){
        editable = false;
    }
    
    initButtons({service:'receipt',htmlName:'receipt?type='+params.type,orderText:txt2,codePrefix:tcode,orderType:0,gridId:'#fixtable_zu'});


    $('#choseOrder').click(function () {

        var relationId = $('input[name="order.relationId"]').val();
        if( relationId == null || $.trim(relationId).length == 0 || relationId == -1 ){
            layer.tips('请先选择'+txt1+'单位', 'input[name="order.relationId_text"]', {
                tips: [1, '#3595CC'],
                time: 3000
            });
            return;
        }

        app.window(layer,{
            title:'源单选择',
            area: ['800px', '600px'],
            content: '../../finance/orgorder_list.html?index=-1&queryId=-1&relationType='+params.relationType+"&relationId="+params.relationId
        });
    });
    $('textarea[name="order.remarks"]').width($('#fixtable_zu').width()-14);
    
    $('#relationId').search({
        name:'order.relationId',
        click:function () {
            app.window(layer,{
                title:txt1+'单位选择',
                btn:[],
                area: ['800px', '600px'],
                content: '../../common/payer_list.html?index=-1&searchId=relationId'
            });
        }
    });

    laydate.render({
        elem: '#order_date',value:app.getServerDate()
    });

    $('#do_reset span').html('新增'+txt2+'单');

    // 必须放在最后  所有代码要写在之前
    if(params.id){
        app.request({
            url:'receipt/getOrder',
            data:{id:params.id},
            success:function (resp) {
                initEdit(resp.data);
            }
        });
    }else{
        $('#order_title').html('新增'+txt2+'单');
        createRow('#fixtable_zu');createRow('#fixtable_zu');
        createRow('#fixtable_ge');createRow('#fixtable_ge');createRow('#fixtable_ge');
    }
}

//编辑初始化
function initEdit(data){
    var order = data.order;
    var accounts = data.accounts;
    var orderOrders = data.orderOrders;

    init_edit_buttons(order,'#fixtable_zu');

    $('#order_add_title').html('编辑'+txt2+'单【'+tcode+order.code+'】');

    $('#order_date').val(app.time2str(parseInt(order.date)));
    $('textarea[name="order.remarks"]').val(order.remarks);
    $('input[name="order.relationId_text"]').val(order.relationName);
    $('input[name="order.relationId"]').val(order.relationId);

    $('#employeeId').combobox('setValue',order.receiptUserId,order.userName);

    for (var i=0 ; i<accounts.length ; i++){
        var account = accounts[i];
        createRow('#fixtable_zu');
        var lastRowEle = $('#fixtable_zu .ctx-right .vui-table-row').last();
        lastRowEle.find('.vui-table-cell[field="name"]').html(account.accountName).data({value:account.accountId,text:account.accountName});
        lastRowEle.find('.vui-table-cell[field="price"]').html(app.div(account.receiptMoney,app.DIV));
        lastRowEle.find('.vui-table-cell[field="remarks"]').html(account.remarks);
    }

    for (var i=0 ; i<orderOrders.length ; i++){
        var orderOrder = orderOrders[i];
        createRow('#fixtable_ge');
        var lastRowEle = $('#fixtable_ge .ctx-right .vui-table-row').last();
        lastRowEle.data({"id":orderOrder.targetId,"code":orderOrder.billCode,"orderType":orderOrder.targetType,"date":orderOrder.billDate,"orderMoney":orderOrder.billPrice,"verificateMoney":orderOrder.verificatedMoney});
        lastRowEle.find('.vui-table-cell[field="orderType"]').html(orderTypeFormat(orderOrder.targetType));
        lastRowEle.find('.vui-table-cell[field="date"]').html(app.time2str(parseInt(orderOrder.billDate)));
        lastRowEle.find('.vui-table-cell[field="code"]').html(codeFormat(orderOrder.targetType)+orderOrder.billCode);
        lastRowEle.find('.vui-table-cell[field="orderMoney"]').html(app.div(orderOrder.billPrice,app.DIV));
        lastRowEle.find('.vui-table-cell[field="verificateMoney"]').html(app.div(orderOrder.verificatedMoney,app.DIV));
        lastRowEle.find('.vui-table-cell[field="xxx"]').html(app.div( app.sub(orderOrder.billPrice,orderOrder.verificatedMoney) ,app.DIV));
        lastRowEle.find('.vui-table-cell[field="currVerificateMoney"]').html(app.div(orderOrder.verificateMoney,app.DIV));
    }
}

function orderTypeFormat(orderType) {
    if( orderType == 22 ){
        return '销售单';
    }else if( orderType == 4 ){
        return '进货退货单';
    }else if( row.orderType == 23 ){
        return '销售退货单';
    }else if( row.orderType == 3 ){
        return '采购单';
    }
}

function codeFormat(orderType) {
    if( orderType == 22 ){
        return 'SH';
    }else if( orderType == 4 ){
        return 'CT';
    }else if( row.orderType == 23 ){
        return 'XT'+row.code;
    }else if( row.orderType == 3 ){
        return 'CG'+row.code;
    }
}

//保存
var accounts = [];
function saveAction(saveType,obj){
    var orderAcctTotalMoney = 0;
    $.each(orderAccounts,function(i,row){
        orderAcctTotalMoney = app.add(orderAcctTotalMoney,row.receiptMoney);
    });


    var ordordTotalMoney = 0;
    $.each(orderOrders,function(i,row){
        ordordTotalMoney = app.add(ordordTotalMoney,row.verificateMoney);
    });

    var data = app.serializeForm();
    data['order.relationType'] = params.relationType;
    data.saveType = saveType;
    data['order.type'] = params.type;
    data['order.isVerificate'] = orderOrders.length > 0 ? 1 : 0;
    data['order.totalMoney'] = app.add(orderAcctTotalMoney,0,0);

    $.each(orderAccounts,function(i,row){
        for ( var n in row ){
            data["accounts["+i+"]."+n] = row[n];
            data["accounts["+i+"].ord"] = i;
        }
    });

    $.each(orderOrders,function(i,row){
        for ( var n in row ){
            data["verificates["+i+"]."+n] = row[n];
            data["verificates["+i+"].ord"] = i;
        }
    });

    var url = 'receipt/insert';
    if(params.id){
        data['order.id'] = params.id;
        url = 'receipt/update';
    }

    if( orderOrders.length>0 && ordordTotalMoney != orderAcctTotalMoney ){
        layer.confirm(txt2+'金额跟核销金额不一致，是否继续？', {icon: 3, title:'提示'}, function(index){
            layer.load();
            doSave(url,data,saveType,obj);
        });
        layer.closeAll('loading');
    }else{
        doSave(url,data,saveType,obj);
    }

}

//表单检查
var orderAccounts = [],orderOrders = [];
function checkForm(){

    var checkOptions = [
        {type:'input',name:'order.relationId_text',verify:[{type:'required'}]},
        {type:'input',name:'order.date',verify:[{type:'required'}]}
    ];

    if(app.checkForm(checkOptions)){

        var tipFlag = false;

        orderAccounts = [];
        $('#fixtable_zu .ctx-right .vui-table-row').each(function () {
            var detail = {};
            var account = $(this).find('.vui-table-cell[field="name"]').data();
            if( account.value ){
                //账户id
                detail.accountId = account.value;
                var price = $(this).find('.vui-table-cell[field="price"]').html();
                // 金额
                if( $.trim(price).length == 0 ){
                    tipFlag = true;
                    app.msg(layer,'账户【'+account.text+'】未填写'+txt2+'金额',2);
                    return false;
                }
                detail.receiptMoney = app.transNumber(app.mul(price,app.DIV));
                // 备注
                detail.remarks = $(this).find('.vui-table-cell[field="remarks"] > div').html();
                orderAccounts[orderAccounts.length] = detail;
            }
        });

        if( tipFlag ){
            return false;
        }else{
            if( orderAccounts.length == 0 ){
                app.msg(layer,'至少填写一条'+txt2+'记录',2);
                return false;
            }
        }

        // order order s
        orderOrders = [];
        var orderOrders_flag = true;
        $('#fixtable_ge .ctx-right .vui-table-row').each(function () {
            var detail = {};
            var row = $(this).data();

            if( row && row.id ){
                detail.billDate = row.date;
                detail.billCode = row.code;
                detail.billPrice = row.orderMoney;
                detail.targetId = row.id;
                detail.targetType = row.orderType;
                detail.verificatedMoney = row.verificateMoney;
                detail.verificateMoney = app.transNumber(app.mul($(this).find('.vui-table-cell[field="currVerificateMoney"]').html(),app.DIV));
                if( parseInt(detail.verificateMoney) > parseInt(app.sub(row.orderMoney,row.verificateMoney)) ){
                    layer.tips('核销金额不能大于未核销金额', $(this).find('.vui-table-cell[field="currVerificateMoney"]'), {
                        tips: [1, '#3595CC'],
                        time: 3000
                    });
                    orderOrders_flag = false;
                }
                orderOrders[orderOrders.length] = detail;
            }
        });

        return orderOrders_flag;
    }

    return false;
}
